package com.cyk.Servlet;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.stream.events.EndDocument;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileItemHeaders;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.tomcat.util.buf.Utf8Encoder;

import com.util.ImageCut;




@WebServlet("/uploadImgServlet")
public class UploadImgServlet extends HttpServlet {
	
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	
		//配置上传的解析类
		FileItemFactory factory = new DiskFileItemFactory(); 
		ServletFileUpload upload = new ServletFileUpload(factory);
		//设置上传文件的大小
		upload.setFileSizeMax(1024*1024);
		
		//设定裁剪图片大小,默认是0
		float x1 = 0,x2=0,y1=0,y2=0,width=0;
		
		boolean isCut =false;
		//	设置上传路劲，需要真实存在
		String path = "c:pic\\";
		String name;
		try {
			//封装表单中的数据到FileItem对象
			List<FileItem> items = upload.parseRequest(request);
			//遍历获取表单数据
			for(int i = 0;i < items.size();i ++){
				
				FileItem item = items.get(i);
				System.out.println(i+" "+item);
				
				if (item.isFormField()) {
					//获取截取后的坐标，四个点，四个方位
					if (item.getFieldName().equals("x1") ) {
						String string = item.getString("utf-8");
						x1 = Float.parseFloat(item.getString("utf-8"));
					}
					if (item.getFieldName().equals("y1") ) {
						y1 = Float.parseFloat(item.getString("utf-8"));
					}
					if (item.getFieldName().equals("x2") ) {
						x2 = Float.parseFloat(item.getString("utf-8"));
					}
					if (item.getFieldName().equals("y2") ) {
						y2 = Float.parseFloat(item.getString("utf-8"));
					}
						width= x2-x1;
						isCut=true;	
				}
				
				//判断是否属于上传文件，如果不属于的话isFormField返回false
				if (!item.isFormField()) {
					/*//获取当前web应用
					ServletContext context = getServletContext();
					//获取应用中此文件夹地址（此处指的是发布在tomcat服务器上的地址）
					URL path = context.getResource("/images");
					System.out.println(path);*/
					
					//获取上传文件的名字
					name = item.getName();
					//假如是同时上传两张或多张，避免上传空图片
					if(name==null || name.trim().equals("")){
						continue;
					}
					//为保证上传图片或文件名字不重复，最好在此时重新生成一个名字
					String beforename= UUID.randomUUID().toString();
					
					//截取上传文件的名字
					String endname = name.substring(name.lastIndexOf(".")+1);
					//重新指定文件（图片名字）
					name = beforename +"." + endname;
					//指定保存路劲（需要c:pic真实存在）					
					File file = new File(path+name);					
					//判断是否已经存在
					if (!file.exists()) {
						try {
							//将文件写进指定目录下
							item.write(file);	
						} catch (Exception e) {
							
							e.printStackTrace();
						}
					}
					//裁剪     调用ImageCut类进行裁剪后的图片重新覆盖写入
					if(isCut){
						ImageCut imageCut = new ImageCut();  
					    imageCut.cutImage(path+name, (int)x1, (int)y1, (int)width, (int)width);
					}
				}
			}
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
